# admission_webhook.py
# 自定义准入控制器，为pod添加一个label标签

# https://kubernetes.io/zh-cn/docs/reference/access-authn-authz/extensible-admission-controllers/

# https://kubernetes.io/zh-cn/docs/reference/command-line-tools-reference/kube-apiserver/

from flask import Flask, request, jsonify
import base64
import jsonpatch
import json

app = Flask(__name__)

@app.route('/mutate', methods=['POST'])
def mutate():
    # 1. 解析 AdmissionReview 请求
    request_data = request.json
    uid = request_data["request"]["uid"]
    pod = request_data["request"]["object"]

    # 2. 检查是否是 Pod 创建请求
    if pod["kind"] == "Pod":
        # 3. 准备要添加的标签
        labels = pod.get("metadata", {}).get("labels", {})
        labels["opswebook"] = "test"

        # 4. 创建 JSON Patch
        patch = [{
            "op": "add" if "labels" not in pod.get("metadata", {}) else "replace",
            "path": "/metadata/labels",
            "value": labels
        }]

        # 5. 构造响应
        return jsonify({
            "apiVersion": "admission.k8s.io/v1",
            "kind": "AdmissionReview",
            "response": {
                "uid": uid,
                "allowed": True,
                "patchType": "JSONPatch",
                "patch": base64.b64encode(json.dumps(patch).encode()).decode()
            }
        })
    else:
        # 非 Pod 资源直接放行
        return jsonify({
            "apiVersion": "admission.k8s.io/v1",
            "kind": "AdmissionReview",
            "response": {
                "uid": uid,
                "allowed": True
            }
        })

if __name__ == '__main__':
    app.run(ssl_context=('ssl/tls.crt', 'ssl/tls.key'), host='0.0.0.0', port=8080)
